# -*- coding: utf-8 *-*
##    This program is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    This program is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with this program.  If not, see <http://www.gnu.org/licenses/>

import os, sys, random, mutagen
from mutagen.easyid3 import EasyID3, error
class MusicFile(object):

    def __init__(self, path):
        self.musiclist = []
        self.path = os.getcwd()
        self.listFile = []

    def listdirectory(self):
        for root, dirs, files in os.walk(self.path):
            for i in files:
                file = os.path.join(root, i)
                if os.path.splitext(file)[1] and os.path.splitext(file)[1] == ".mp3":
                    self.listFile.append(os.path.join(root, i))

    def findMusic(self):
        del(self.musiclist[:])
        del(self.listFile[:])
        self.listdirectory()
        print len(self.listFile)

    def extractId3(self):
        id = 1
        for file in self.listFile:
            music = {}
            audio = EasyID3(file)
            file_path = ''.join(file)
            music['path'] = file_path.decode('iso-8859-1').encode('utf8')
            music['id'] = str(id).zfill(3).encode('utf8');
            try:
                music['artist'] = ''.join(audio['artist']).encode('utf8')
            except KeyError:
                music['artist'] = 'Unknown Artist'.encode('utf8')
            try:
                music['album'] = ''.join(audio['album']).encode('utf8')
            except KeyError:
                music['album'] = 'Unknown Album'.encode('utf8')
            try:
                music['genre'] = ''.join(audio['genre']).encode('utf8')
            except KeyError:
                music['genre'] = 'Unknown Genre'.encode('utf8')
            try:
                title = ''.join(audio['title'])
                music['title'] = title.encode('utf8')
            except KeyError:
                music['title'] = 'Unknown Title'.encode('utf8')
            try:
                music['tracknumber'] = ''.join(audio['tracknumber']).encode('utf8')
            except KeyError:
                music['tracknumber'] = '1'.encode('utf8')
            self.musiclist.append(music)
            id += 1
            
    def affMusicList(self):
        print "--------------------------> BEGIN LIST"
        for i in self.musiclist:
            print i
        print "--------------------------> END LIST"

    def randomList(self):
        random.shuffle(self.musiclist)
        
    def sortListFromParam(self, param):
        self.musiclist.sort(lambda x,y: cmp(x[param],y[param]))
        
    def sortReverseListFromParam(self, param):
        self.musiclist.sort(lambda x,y: cmp(y[param],x[param]))

    def wFUtf8(self, filename, text):
        filename.write(text)
        
    def generateXml(self):
        f = open("id3.xml", "w")
        self.wFUtf8(f, '<?xml version="1.0" encoding="UTF-8"?>\n<Root>\n')
        self.generateXmlMedia(f)
        self.wFUtf8(f, '<Sort>')
        self.generateXmlSort(f)
        self.wFUtf8(f, '</Sort>\n')
        self.wFUtf8(f, '</Root>\n')
        f.close()

    def generateXmlSort(self, f):
	pos = 1
        for i in self.musiclist:
            xml = str(int(i['id']))
            if pos < len(self.musiclist):
                xml += ','
            self.wFUtf8(f, xml)
	    pos += 1

    def generateXmlMedia(self, f):
        rep_cour = os.getcwd()
        ##id = 1
        for i in self.musiclist:
            xml = "<Media Path=\""
            xml += i['path'].replace(rep_cour, '')
            xml += '" Index="'
            xml += str(int(i['id']))
            xml += '">\n<Artists>'
            xml += i['artist']
            xml += '</Artists>\n<Album>'
            xml += i['album']
            xml += '</Album>\n<Genre>'
            xml += i['genre']
            xml += '</Genre>\n<Title>'
            xml += i['title']
            xml += '</Title>\n<Track>1</Track>\n<TrackNum>1</TrackNum>\n</Media>\n'
            self.wFUtf8(f, xml)
            ##id += 1

